package com.dashan.looperpager.sensor;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.PowerManager;
import android.util.Log;

import com.dashan.looperpager.TestApplication;

public class SensorUtils implements SensorEventListener {

    public static final String TAG = "SensorUtils";

    //传感器管理对象
    private SensorManager mManager;

    //屏幕开关 电源管理对象
    private PowerManager localPowerManager;
    //电源锁
    private PowerManager.WakeLock wakeLock;

    private static class SingleTonHolder {
        private static SensorUtils INSTANCE = new SensorUtils();
    }

    public static SensorUtils getInstance() {
        return SingleTonHolder.INSTANCE;
    }

    @SuppressLint("InvalidWakeLockTag")
    public SensorUtils() {
        Context context = TestApplication.getAppContext();
        mManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        //获取系统服务POWER_SERVICE，返回一个PowerManager对象
        localPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        //获取PowerManager.WakeLock对象
        //第一个参数为电源锁级别，第二个是日志tag
        wakeLock = localPowerManager.newWakeLock(32, "MyPower");
    }

    /**
     * 注册传感器
     */
    public void register() {
        //参数 ：距离监听器，传感器类型，延迟类型
        mManager.registerListener(this, mManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    /**
     * 注销传感器监听
     */
    public void release() {
        if (mManager != null) {
            wakeLock.release();
            mManager.unregisterListener(this);
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        Log.d(TAG, "感应了...");
        if (event.values != null && event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
            if (event.values[0] == 0.0) {
                Log.d(TAG, "贴近手机");
                if (!wakeLock.isHeld()) {
                    wakeLock.acquire();
                }
            } else {
                Log.d(TAG, "远离手机");
                if (wakeLock.isHeld()) {
                    wakeLock.release();
                }
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //自动生成的方法存根
    }

}
